package com.dfs.parent.common.feign.context;

import cn.hutool.core.util.StrUtil;
import com.dfs.parent.common.core.constant.GrayConstant;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GrayContextHolderFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //不需要服务发现的元数据开关判断，可能是这个服务不需要灰度，下一个服务需要做灰度，问题：如果灰度开关每打开也会选择所有实例，可能找不到下一个开关
        String grayTag = request.getHeader(GrayConstant.GRAY_HEADER_TAG);
        try {
            if (StrUtil.isNotEmpty(grayTag)) {
                GrayContextHolder.setGrayTag(grayTag);
            }
            chain.doFilter(request, response);
        } finally {
            GrayContextHolder.remove();
        }
    }
}
